package org.fly.service.impl;


import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.fly.bean.AliSmsSetting;
import org.fly.bean.SmsRecord;
import org.fly.bean.SmsTemplate;
import org.fly.bean.common.BusinessException;
import org.fly.bean.query.SmsRecordQuery;
import org.fly.contants.ErrorConstant;
import org.fly.contants.WebConstant;
import org.fly.dao.AliSmsSettingDao;
import org.fly.dao.SmsRecordDao;
import org.fly.dao.SmsTemplateDao;
import org.fly.enums.SmsType;
import org.fly.service.SmsRecordService;
import org.fly.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Created by autoCode on 2018-04-10 15:19:44.
*/
@Service
public class SmsRecordServiceImpl implements SmsRecordService {

@Autowired
SmsRecordDao smsRecordDao;
@Autowired

AliSmsSettingDao aliSmsSettingDao;
@Autowired
SmsTemplateDao smsTemplateDao;



@Override
public List<SmsRecord> list(SmsRecordQuery query) {
        return smsRecordDao.list(query);
    }

    @Override
    public long count(SmsRecordQuery query) {
        return smsRecordDao.count(query);
    }

    @Override
    public SmsRecord findById(String id) {
        return smsRecordDao.findById(id);
    }

    @Override
    public void save(SmsRecord bean)  throws BusinessException {

        if(StringUtils.isNotBlank(bean.getId())){
             smsRecordDao.update(bean);
        }else {
            bean.setId(UUIDFactory.random());
            bean.setCreateTime(System.currentTimeMillis());
            smsRecordDao.insert(bean);
        }
    }

    @Override
    public void delete(String id) {
        smsRecordDao.delete(id);
    }

    @Transactional
    @Override
    public void sendVerify(String telephone) throws BusinessException{
        if(!TelephoneUtils.check(telephone)){
            throw new BusinessException(ErrorConstant.ec_telephone_error,
                    ErrorConstant.em_telephone_error);
        }
        SmsRecordQuery query = new SmsRecordQuery();
        query.setSize(1);
        query.setPage(1);
      /*  query.setSize(1);
        query.setOffset(0);*/
        query.setTelephone(telephone);
        List<SmsRecord> list = this.smsRecordDao.list(query);
        if(CollectionUtils.isNotEmpty(list)){
            if(list.size()>0){
                SmsRecord smsRecord = list.get(0);
                Long diff = System.currentTimeMillis() - smsRecord.getCreateTime();
                if((diff/1000)<(30*60)){
                    throw new BusinessException(ErrorConstant.ec_sms_limit,
                            ErrorConstant.em_sms_limit);
                }
            }
        }
        try{
            Map<String,Object> param = new HashMap<>();
            String code = StringUtil.getNumRandomCode(6);
            SmsType smsType= SmsType.verification;
            SmsTemplate smsTemplate = smsTemplateDao.findByType(smsType.name());
            param.put("code",code);
            sendSms(telephone,SmsType.verification,smsTemplate.getAliTemplateCode(),param);
        }catch (Exception e){
            throw new BusinessException(ErrorConstant.ec_system_error,
                    ErrorConstant.em_system_error);
        }

    }

    @Override
    public void sendSms(String telephone,SmsType smsType ,String templateId, Map<String, Object> param) throws BusinessException {
        try{
            AliSmsSetting smsSetting = aliSmsSettingDao.find();
            String code = null;
            if(SmsType.verification == smsType){
                code = (String) param.get("code");
            }else {
                code = StringUtil.getNumRandomCode(6);
            }
            String uuid =  UUIDFactory.random();
            String jsonParam = JsonUtils.encode(param);
            boolean flag =  SmsSendUtil.sendMessage(smsSetting,telephone,
                    templateId,
                    jsonParam ,
                    uuid);
            //todo 暂时不加入验证码发送是否成功的判断
            if(flag){
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setId(uuid);
                smsRecord.setType(smsType.name());
                smsRecord.setTelephone(telephone);
                smsRecord.setValue(code);
                smsRecord.setContent("");
                smsRecord.setCreateTime(System.currentTimeMillis());
                smsRecordDao.insert(smsRecord);
            }else {
                throw new BusinessException(10000,"短信发送失败");
            }
            /*if(resultTip.isSuccess()){*/

            /*}*/
        }catch (Exception e){
            throw new BusinessException(ErrorConstant.ec_system_error,
                    ErrorConstant.em_system_error);
        }
    }

    public boolean checkVerifyCode(String telephone,String verifyCode){
        boolean check = false;
        SmsRecordQuery query = new SmsRecordQuery();
        query.setTelephone(telephone);
        query.setType(SmsType.verification.name());
        query.setSize(1);
        query.setPage(1);
        List<SmsRecord>  smsRecords = smsRecordDao.list(query);
        SmsRecord smsRecord =  smsRecords.get(0);
        Long diff = System.currentTimeMillis() - smsRecord.getCreateTime();
        if((diff/1000)<(30*60) && verifyCode.equals(smsRecord.getValue())){
            check =  true;
        }
        return check;
    }
}
